<template>
  <a-switch v-model:checked="value" :loading="loading" @change="handleChange" />
</template>

<script>
import useHttp from '@/hook/use-http'
import {defineComponent, ref, watch} from "vue";
import {useVModel} from "@vueuse/core";
export default defineComponent({
  name: "ExSwitch",
  props:{
    checked:[Number,String,Boolean],
    url: String,
    params:{
      type:Object,
      default: {},
    },
    field:String,
  },
  emits:['update:checked'],
  setup(props,ctx){
    const {loading, http} = useHttp()
    const value = useVModel(props,'checked',ctx.emit)
    const checkedValue = ctx.attrs.checkedValue === undefined ? true:ctx.attrs.checkedValue
    const unCheckedValue = ctx.attrs.unCheckedValue === undefined ? false:ctx.attrs.unCheckedValue
    if(value.value === false){
      value.value = unCheckedValue
    }else if(value.value === true){
      value.value = checkedValue
    }
    function handleChange(checked){
      ctx.emit('change',checked)
      let failValue
      if(checked == checkedValue){
        failValue = unCheckedValue
      }else{
        failValue = checkedValue
      }
      let params = props.params
      if(!params.data){
        params.data = {}
      }
      params.data[props.field] = checked
      if(props.url){
        http({
          url:props.url,
          method: 'put',
          data: params
        }).then(res=>{
          ctx.emit('update:checked',checked)
        }).catch(res=>{
          value.value = failValue
          ctx.emit('update:checked',failValue)
        })
      }else{
        ctx.emit('update:checked',checked)
      }
    }
    return {
      handleChange,
      loading,
      value,
    }
  }
})
</script>

<style scoped>

</style>
